//
//  KFDAddressAccessor.m
//  KFD
//
//  Created by JIRENTIANXIANG on 7/9/15.
//  Copyright © 2015 kfd. All rights reserved.
//

#import "KFDAddressbook.h"
#import "KFDClient.h"

@interface KFDAddressbook ()

@property (strong,atomic) NSDictionary* addressBook;

@end

@implementation KFDAddressbook

-(instancetype)init
{
    if (self=[super init]) {
        NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
        NSDictionary* address=[defaults dictionaryForKey:@"address"];
        if (address) {
            self.addressBook=address;
        }else{
            KFDClient* client=[KFDClient sharedClient];
            [client getAddressWithSuccessHandler:^(NSDictionary *addressResource) {
                self.addressBook=addressResource;
            } failureHandler:^(KFDResponseBody *response) {
                
            }];
        }
    }
    return self;
}

-(NSArray*)provinces
{
    if (!_provinces) {
        NSMutableArray* provinces=[NSMutableArray array];
        NSDictionary* dict=self.addressBook[@"area0"];
        NSEnumerator* enumerator=dict.keyEnumerator;
        for (NSString* key in enumerator) {
            KFDAddress* address=[[KFDAddress alloc] init];
            address.number=key;
            address.name=dict[key];
            [provinces addObject:address];
        }
        _provinces=provinces;
    }
    return _provinces;
}

-(NSArray*)citiesInProvince:(NSString *)province
{
    NSMutableArray* cities=[NSMutableArray array];
    NSDictionary* dict=self.addressBook[@"area1"];
    NSArray* arr=dict[province];
    for (NSArray* subArr in arr) {
        KFDAddress* city=[[KFDAddress alloc] init];
        city.name=subArr[0];
        city.number=subArr[1];
        [cities addObject:city];
    }
    return cities;
}

-(NSArray*)districtsInCity:(NSString *)city
{
    NSMutableArray* districts=[NSMutableArray array];
    NSDictionary* dict=self.addressBook[@"area2"];
    NSArray* arr=dict[city];
    for (NSArray* subArr in arr) {
        KFDAddress* district=[[KFDAddress alloc] init];
        district.name=subArr[0];
        district.number=subArr[1];
        [districts addObject:district];
    }
    return districts;
}

-(void)dealloc
{
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    NSDictionary* address=[defaults dictionaryForKey:@"address"];
    if (!address) {
        [defaults setObject:self.addressBook forKey:@"address"];
    }
}

@end

//------------------------------------------------------------------------------
// KFDAddress
//------------------------------------------------------------------------------
@implementation KFDAddress

@end
//------------------------------------------------------------------------------